package webTest.sessionCookie.LastView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * Created by IFT8 on 2015/1/26.
 *
 */
public class Index extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        response.setContentType("text/html;charset=utf-8");
        //显示书库
        Map<String, Book> books = BookDAO.getBooks();
        for (Map.Entry<String, Book> entry : books.entrySet()) {
            Book book = entry.getValue();
            //获取URL路径
            response.getWriter().print("<a href='" + request.getContextPath() + "BookInfo?id=" + book.getId() + "'>");
            response.getWriter().print(book.getName() + "</a><br>");
        }
        response.getWriter().print("&emsp;&emsp;&emsp;<a href='" + request.getContextPath() + "CleanCookie'>[清除Cookie]</a>");
        //华丽分割线
        response.getWriter().print("<hr>");
        //上次看过的书
        Cookie[] cookies = request.getCookies();
        String lastView=null;
        if (cookies == null) {
            response.getWriter().print("没有浏览记录");
        } else {
            for (Cookie cookie1 : cookies) {
                if ("lastView".equals(cookie1.getName())) {
                    lastView = cookie1.getValue();
                    break;
                }
            }
            if (lastView == null) {
                response.getWriter().print("没有浏览记录");
                return;
            }
            String[] lastViews = lastView.split(",");
            response.getWriter().print("上次看的书为: &emsp;"); //&emsp;相当于/t
            //逆序显示，即浏览的顺序显示
            for (int i = lastViews.length-1; i >=0 ; i--) {
                Book book=BookDAO.getBook(lastViews[i]);
                if(book!=null){
                    response.getWriter().print(book.getName()+"&emsp;");
                }
            }
        }
    }
}
